<template>
    <div class="level-manage-main">
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="calc(100vh - 232px)"
            :show-pagination="false"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @updateData="getTableData">
            <template #headerOperate>
                <div class="gc-content">
                    <div class="right">
                        <el-button v-auth="'ADD_LEVEL'" type="primary" @click="handlerAddLevel"> 添加等级 </el-button>
                    </div>
                </div>
            </template>
        </ZwTable>
        <ZWDeleteDialog ref="deleteDialogRef" @submit="deleteSubmit" />
        <Dialog :app-dialog="appDialog">
            <div>
                <div class="dialog_content_title">
                    <el-icon class="dialog_icon">
                        <WarningFilled />
                    </el-icon>
                    <div>{{ dialogInfo.title }}</div>
                </div>
                <div class="dialog_content_desc">
                    {{ dialogInfo.content }}
                </div>
            </div>
        </Dialog>
    </div>
</template>
<script setup lang="tsx">
import { ref, reactive, computed } from 'vue';
import { deepCopy } from '@/utils/helper';
import { useRouter } from 'vue-router';
import { ElMessage, ElButton } from 'element-plus';
import { Picture as IconPicture, WarningFilled } from '@element-plus/icons-vue';
import { getMemberLevelList, changeSwitchMemberLevel, delMemberLevel } from '@/api/member/memberLevel/index';
import ZwTable from '@/components/zw/table/Table';
import ZWDeleteDialog from '@/components/ZWDeletdialog.vue';
import Dialog from '@/components/Dialog.vue';

const router = useRouter();

const tableRef = ref<any>(null);
const deleteDialogRef = ref<any>(null);

const tableList = ref<any>([]);

const cancelHandel = () => {
    appDialog.visible = false;
};

const submitHandel = async () => {
    const params = {
        id: dialogInfo.id,
        switch: dialogInfo.type
    };
    const res = await changeSwitchMemberLevel(params);
    ElMessage.success('设置成功');
    appDialog.visible = false;
    tableRef.value.reload();
};

const appDialog = reactive<any>({
    visible: false,
    title: '提示',
    width: '30%',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});

const delInfo = reactive<any>({
    id: ''
});

const dialogInfo = reactive<any>({
    type: ''
});

const tableOption = [
    {
        prop: 'member_level',
        label: '会员等级',
        width: 150
    },
    {
        prop: 'member_level_name',
        label: '会员名称',
        width: 150
    },
    {
        prop: 'member_uplevel_condition',
        label: '升级条件',
        width: 140,
        render({ row, column, index }: any) {
            return <div>{plevenCondition(row)}</div>;
        }
    },
    {
        prop: 'member_priority_list',
        label: '会员权益',
        width: 160,
        render({ row, column, index }: any) {
            if (row.member_priority_list.length) {
                return (
                    <>
                        {row.member_priority_list.map((el: any) => {
                            return <div>{el.priority_inner_name}</div>;
                        })}
                    </>
                );
            } else {
                return <div>-</div>;
            }
        }
    },
    {
        prop: 'member_uplevel_gift',
        label: '升级礼包',
        width: 120,
        render({ row, column, index }: any) {
            return (
                <div>
                    {row.member_uplevel_gift.bonus_points_point
                        ? `${row.member_uplevel_gift.bonus_points_point}积分`
                        : '-'}
                </div>
            );
        }
    },
    {
        prop: 'member_num',
        label: '会员数',
        width: 200
    },
    {
        prop: 'switch',
        label: '状态',
        minWidth: 200,
        render({ row, column, index }: any) {
            return (
                <div className={`${row.switch == 1 ? 'status_green status' : 'status'}`}>
                    {row.switch == 1 ? '已启用' : '已停用'}
                </div>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 290,
        isOperate: true,
        render({ row, column, index }: any) {
            return (
                <div class="zw-table__btn-box">
                    <ElButton size="small" vAuth={'EDIT'} onClick={() => handlerEdit(row)}>
                        编辑
                    </ElButton>
                    {index > 0 && row.switch == 2 && row.member_uplevel_condition == listInfo.maxFalse && (
                        <ElButton size="small" vAuth={'DEL'} onClick={() => handlerDel(row)}>
                            删除
                        </ElButton>
                    )}
                    {index > 0 && row.switch == 2 && row.member_uplevel_condition == listInfo.minFalse && (
                        <ElButton vAuth={'ENABLE'} size="small" onClick={() => handlerStatus(row)}>
                            启用
                        </ElButton>
                    )}
                    {index > 0 && row.switch == 1 && row.member_uplevel_condition == listInfo.maxTrue && (
                        <ElButton vAuth={'STOP'} size="small" onClick={() => handlerStatus(row)}>
                            停用
                        </ElButton>
                    )}
                </div>
            );
        }
    }
];

const defaultParams = {};

const state = reactive({
    searchParams: deepCopy(defaultParams)
});

const getRowKey = (row: any) => {
    return row.id;
};

const fetchApi = () => {
    return getMemberLevelList;
};

const listInfo = reactive<any>({
    minFalse: 0,
    maxFalse: 0
});

const getTableData = (val?: any) => {
    tableList.value = val || [];
    const falseArr: any = [];
    const trueArr: any = [];
    tableList.value.forEach((item: any) => {
        item.switch === 1 ? trueArr.push(item) : falseArr.push(item);
    });
    if (falseArr.length > 0) {
        listInfo.minFalse = falseArr[0].member_uplevel_condition;
        listInfo.maxFalse = falseArr[falseArr.length - 1].member_uplevel_condition;
    }
    if (trueArr.length > 0) {
        listInfo.minTrue = trueArr[0].member_uplevel_condition;
        listInfo.maxTrue = trueArr[trueArr.length - 1].member_uplevel_condition;
    }
};

const deleteSubmit = async () => {
    const params = {
        id: delInfo.id
    };
    const res = await delMemberLevel(params);
    if (res) {
        ElMessage.success('删除成功');
        deleteDialogRef.value.appDialog.visible = false;
        tableRef.value.reload();
    }
};

const handlerAddLevel = (val: any) => {
    if (tableList.value.length === 10) {
        ElMessage.warning('最多添加10个会员等级');
        return;
    }
    router.push({
        path: '/member/memberLevel/levelManage/addLevel',
        query: {
            type: 'add',
            level: tableList.value.length + 1,
            upLevel: tableList.value[tableList.value.length - 1]?.member_uplevel_condition
        }
    });
};

const handlerEdit = (val: any) => {
    router.push({
        path: '/member/memberLevel/levelManage/addLevel',
        query: { type: 'edit', id: val.id }
    });
};

const handlerDel = (val: any) => {
    delInfo.id = val.id;
    deleteDialogRef.value.content = `确定要删除${val.member_level_name}等级吗？`;
    deleteDialogRef.value.appDialog.visible = true;
};

const handlerStatus = (val: any) => {
    dialogInfo.id = val.id;
    dialogInfo.type = val.switch == 1 ? 2 : 1;
    if (val.switch === 2) {
        dialogInfo.title = `确定要启用${val.member_level}等级吗？`;
        dialogInfo.content = `启用${val.member_level}等级后，会员等级将重新计算，原${val.member_level}等级的会员可能会发生等级变动。`;
    } else {
        dialogInfo.title = `确定要停用${val.member_level}等级吗？`;
        dialogInfo.content = `停用${val.member_level}等级后，原${val.member_level}等级的会员将会降级，请谨慎操作，避免引起客诉。`;
    }
    appDialog.visible = true;
};

/**
 * @description: 升级条件
 * @param {*} val
 * @return {*} 升级条件
 */
const plevenCondition = (val: any) => {
    if (val.member_uplevel_condition && val.member_uplevel_condition <= 99999999) {
        return `${val.member_uplevel_condition}成长值`;
    } else if (!val.member_uplevel_condition) {
        return '无门槛';
    } else if (val.member_uplevel_condition > 99999999) {
        return `99999999成长值`;
    }
};
</script>
<style lang="scss" scoped>
.level-manage-main {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }

    :deep(.status) {
        display: flex;
        align-items: center;

        &::before {
            display: inline-block;
            width: 8px;
            height: 8px;
            margin-right: 6px;
            content: '';
            border-radius: 4px;
            background: #ccc;
        }
    }

    :deep(.status_green::before) {
        background: #32d1ad;
    }

    .dialog_content_title {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        font-size: 14px;

        .dialog_icon {
            margin-right: 9px;
            color: #faad14;
            font-size: 14px;
        }
    }

    .dialog_content_desc {
        padding-left: 23px;
        color: #969696;
        font-size: 14px;
        line-height: 20px;
    }
}
</style>
